package com.fjh.service;

import com.fjh.pojo.Activity;
import com.fjh.repository.ActivityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;


@Service
public class ActivityService {

    @Autowired
    private ActivityRepository activityRepository;

    public Activity createActivity(Activity activity) {
        activity.setCreatedTime(new Date());
        return activityRepository.save(activity);
    }

    public Activity updateActivity(Activity activity) {
        Optional<Activity> existingActivity = activityRepository.findById(activity.getId());
        if (existingActivity.isPresent()) {
            return activityRepository.save(activity);
        } else {
            throw new RuntimeException("Activity not found for update with ID: " + activity.getId());
        }
    }


    public void publishActivity(Long activityId) {
        Optional<Activity> optionalActivity = activityRepository.findById(activityId);
        if (optionalActivity.isPresent()) {
            Activity activity = optionalActivity.get();
            activity.setStatus(1); // 设置为已发布
            activityRepository.save(activity);
        } else {
            throw new RuntimeException("Activity not found for publish with ID: " + activityId);
        }
    }
        public List<Activity> getAllActivities() {
            return activityRepository.findAll();
        }



    public List<Activity> searchActivities(String name, Integer status) {
        if (name != null && status != null) {
            // 如果同时提供了名称和状态，按照名称和状态进行查询，并按创建时间降序排序
            return activityRepository.findByNameContainingAndStatusOrderByIdDesc(name, status);
        } else if (name != null) {
            // 如果只提供了名称，按照名称进行查询，并按创建时间降序排序
            return activityRepository.findByNameContainingOrderByIdDesc(name);
        } else if (status != null) {
            // 如果只提供了状态，按照状态进行查询，并按创建时间降序排序
            return activityRepository.findByStatusOrderByIdDesc(status);
        } else {
            // 如果没有提供名称和状态，只按照创建时间降序排序
            return activityRepository.findAllByOrderByIdDesc();
        }
    }


    public Activity findActivityById(Long activityId) {
        Optional<Activity> optionalActivity = activityRepository.findById(activityId);
        return optionalActivity.orElse(null);
    }
}

